//
// ServerAdmin.cpp
//

/*-----------------------------------------------------*\
			HQ Tech, Make Technology Easy!       
 More information, please go to http://hqtech.nease.net.
/*-----------------------------------------------------*/

#include "stdafx.h"
#include <streams.h>
#include "ServerAdmin.h"
#include "GlobalDefs.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////
ServerAdmin::ServerAdmin() : mStatus(STATUS_NONE)
{
	// Receive message from TCP Listener
	mTcpListener.AddMsgReceiver(this);
}

ServerAdmin::~ServerAdmin()
{
	Finalize();
}

BOOL ServerAdmin::Initialize(void)
{
	mUdpManager.SetLocalPort(SERVER_UDP_PORT);

	BOOL pass = CRoleAdmin::Initialize();

	// Start TCP listening on the client
	if (pass)
	{
		mTcpListener.SetListenPort(SERVER_TCP_PORT);
		pass = mTcpListener.Create();
	}
	if (pass)
	{
		pass = mTcpListener.StartListening();
	}
	if(pass)
	{
		mStatus = STATUS_STANDBY;
	}
	return pass;
}

void ServerAdmin::Finalize(void)
{
	mTcpListener.StopListening();

	CRoleAdmin::Finalize();
}

BOOL ServerAdmin::Call(AgentSession *pSession)
{
	if(mStatus != STATUS_STANDBY)
	{
		return FALSE;
	}

	UdpPackCall pack;
	pack.wdPort = SERVER_TCP_PORT;
	BOOL pass = SendUdpCmd(pSession, &pack);

	if(pass)
	{
		mStatus = STATUS_CALLING;
	}
	return pass;
}

void ServerAdmin::EndCall(BOOL inNotifyPeer)
{
	// Notify the remote to disconnect
	if (inNotifyPeer)
	{
		UdpPackEndCall pack;
		SendUdpCmd(pSession, &pack);
	}

	Deactivate();

	mStatus = STATUS_STANDBY;
}

BOOL ServerAdmin::OnRecvUdpCmd(AgentSession *pSession, const UdpPack *pPack)
{
	time_t now = ::time(NULL);
	pSession->
	switch (pPack->dwCmd)
	{
	case CMD_HEART_BEAT:
		{
			const UdpPackHeartBeat *pCmd = (const UdpPackHeartBeat *)pPack;
			pSession->SetHostName(pCmd->szHostName);
			pSession->SetDeviceConfig(pCmd->dwDeviceConfig);
			Broadcast(msg_RefreshAgent, pSession);
		}
	}
}

BOOL ServerAdmin::OnTcpAccept()
{
	if (mTcpListener.IsSocketReady())
	{
		// Make the server begin to build filter graph
		SendSimpleCommand(cmd_BuildFilterGraph);
		// Now the client must begin to build filter graph too
		BOOL isBuilding = TRUE;
		Broadcast(msg_ModifyFilterGraph, &isBuilding);
	}
}

SOCKET ServerAdmin::GetVideoStreamSocket(void)
{
	return mTcpListener.GetAccepted(0);
}

SOCKET ServerAdmin::GetAudioStreamSocket(void)
{
	return mTcpListener.GetAccepted(1);
}

